/**
 * Copyright (c) 2014-2015, Suredy technology Co., Ltd. All rights reserved.
 * @author ZhangMaoren 
 * @since 2015年9月15日
 * @version 0.1
 */
package com.suredy.compoent;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.core.mvc.model.MessageModel;


/**
 * @author ZhangMaoren
 *
 */
@Controller
@RequestMapping(value = "/component")
public class UploaderCtrl extends BaseCtrl{
	private final static Logger log = LoggerFactory.getLogger(UploaderCtrl.class);
	
	@RequestMapping("uploader")
	@ResponseBody
	public Object doUpload(HttpServletRequest request) {
		//存储目录
		String basePath = new File(request.getServletContext().getRealPath("upload")).getAbsolutePath();
		String storage = request.getParameter("storage");
		File storagePath;
		if (StringUtils.isBlank(storage)) {
			storagePath = new File(basePath);
		} else {
			storagePath = new File(basePath + File.separator + storage);
		}
		if (!storagePath.exists()) {
			storagePath.mkdir();
		}
		// 临时目录
		File tempPath = new File(basePath + File.separator + "temp");
		if (!tempPath.exists()) {
			tempPath.mkdir();
		}
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置文件的下限
		factory.setSizeThreshold(4 * 1024);
		// 设置中转目录
		factory.setRepository(tempPath);

		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UFT-8");
		// 设置上传文件的上限
		upload.setSizeMax(1024 * 1024 * 512);
		StringBuffer sb = new StringBuffer();
		try {
			List<FileItem> fileItems = upload.parseRequest(request);
			for (Iterator<FileItem> iter = fileItems.iterator(); iter.hasNext();) {
				FileItem item =  iter.next();
				// 是否为input="type"输入域
				if (!item.isFormField()) {
					String fileName = item.getName();
					long size = item.getSize();
					if ((fileName == null || fileName.equals("")) && size == 0) {
						continue;
					}
					// 截取字符串 如：C:\WINDOWS\Debug\PASSWD.LOG
					fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1, fileName.length());
					item.write(new File(storagePath, fileName));
					sb.append(",").append(fileName);
					//TODO
				} else {
					//TODO 普通文本域
					continue;
				}
			}
			
		} catch (Exception e) {
			log.info("Failed to upload Excel file.");
			return MessageModel.createErrorMessage("操作失败: 上传Excel文件失败...", null);
		}
		return MessageModel.createSuccessMessage(null, sb.substring(1));
	}

}
